package org.leviatan.dataharbour.gui.listeners;

import java.util.TreeSet;
import java.util.Vector;

import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

import org.leviatan.dataharbour.core.model.DataSource;
import org.leviatan.dataharbour.gui.RuntimeContext;
import org.leviatan.dataharbour.gui.swingmodels.TreeNodeMdlDataSource;

public class DataSourceTreeListener implements TreeSelectionListener {
	
	private JTree theTree = null;

	public DataSourceTreeListener(JTree aTree) {
		this.theTree = aTree;
	}
	
	public void valueChanged(TreeSelectionEvent e) {
		DefaultMutableTreeNode selectedNode = 
			(DefaultMutableTreeNode) theTree.getLastSelectedPathComponent();

		if (selectedNode == null) return;
	
		Object nodeModel = selectedNode.getUserObject();
		
		
		if (selectedNode instanceof TreeNodeMdlDataSource) {
			
			String dataSourceId = ((TreeNodeMdlDataSource) selectedNode).getId();
			
			DataSource dataSourceMdl = 
				RuntimeContext.dataHarbourService.getDataSource(dataSourceId);
			
			Vector defs = RuntimeContext.dataHarbourService.getDataSourcesDefs(dataSourceId);
			if (defs == null) defs = new Vector(0);
			RuntimeContext.defsList.setListData(defs);
			
			TreeSet persRes = RuntimeContext.dataHarbourService.getDataSourcesPersistenceResourceKeys(dataSourceId);
			
			if (persRes == null) persRes = new TreeSet();
			RuntimeContext.persResList.setListData(persRes.toArray());
		}
			
	}

}
